#pragma once // 确保头文件只被包含一次，防止重复定义

#include <iostream>    // 提供输入输出流支持
#include <cerrno>      // 定义错误代码变量errno
#include <cstring>     // 提供字符串处理函数，如strerror
#include <cstdlib>     // 包含exit函数及其他实用工具函数
#include <string>      // C++字符串类支持
#include <sys/ipc.h>   // 提供IPC函数，如ftok
#include <sys/shm.h>   // 提供共享内存的API，如shmget, shmat等
#include <sys/types.h> // 提供数据类型支持，比如key_t
#include <cstdint>

using namespace std; // 使用标准命名空间，避免每次使用std::前缀
const char *pathname = "/home/lsy";
const int proj_id = 0x66;
const int defaultsize = 4096;
std::string ToHex(key_t k)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", k);
    return buffer;
}

key_t GetShmKeyOrDie()
{
    key_t k = ftok(pathname, proj_id);
    if (k < 0)
    {
        std::cerr << "ftok error,error: " << errno << ",error string:" << strerror(errno) << std::endl;
        exit(1);
    }
    return k;
}

int CreateShmOrDie(key_t key, int size, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        std::cerr << "shmget error,errno: " << errno << ",error string:" << strerror(errno) << std::endl;
        exit(1);
    }
    return shmid;
}

int CreateShm(key_t key, int size)
{
    return CreateShmOrDie(key, size, IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm(key_t key, int size)
{
    return CreateShmOrDie(key, size, IPC_CREAT | 0666);
}

void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if (n < 0)
    {
        std::cerr << "shmctl error" << std::endl;
    }
    else
    {
        std::cout << "shmctl delete shm success,shmid" << shmid << std::endl;
    }
}
void ShmDebug(int shmid)
{
    struct shmid_ds shmds;
    int n = shmctl(shmid, IPC_STAT, &shmds);
    if (n < 0)
    {
        std::cerr << "shmctl error" << std::endl;
    }
    std::cout << "shmds.shm_segsz: " << shmds.shm_segsz << std::endl;
    std::cout << "shmds.shm_nattch:" << shmds.shm_nattch << std::endl;
    std::cout << "shmds.shm_ctime:" << shmds.shm_ctime << std::endl;
    std::cout << "shmds.shm_perm.__key:" << ToHex(shmds.shm_perm.__key) << std::endl;
}

void *ShmAttach(int shmid)
{
    void *addr = shmat(shmid, nullptr, 0);
    if ((long long int)addr == -1)
    {
        std::cerr << "shmat error" << std::endl;
        return nullptr;
    }
    return addr;
}
void ShmDetach(void *addr)
{
    int n = shmdt(addr);
    if (n < 0)
    {
        std::cerr << "shmdt error" << std::endl;
    }
}